#!/bin/bash

###SHELLPACK preamble tlbflush-install 0

###SHELLPACK parseargBegin
###SHELLPACK parseargEnd

mkdir -p $SHELLPACK_SOURCES/tlbflush-${VERSION}-installed
cd $SHELLPACK_SOURCES/tlbflush-${VERSION}-installed || die Failed to create install directory
wget -O tlbflush.c.in "http://marc.info/?l=linux-kernel&m=133727348217113&q=raw" || die Failed to download source code

START_LINE=`grep -n ^---$ tlbflush.c.in | cut -f1 -d:`
END_LINE=`grep -n ^--$ tlbflush.c.in | cut -f1 -d:`
head -$((END_LINE-1)) tlbflush.c.in | tail -$((END_LINE-START_LINE-1)) | grep -v "define FILE_SIZE" > tlbflush.c

echo '--- tlbflush.c.orig	2013-12-15 11:05:08.813821030 +0000
+++ tlbflush.c	2013-12-15 11:04:46.504926426 +0000
@@ -67,13 +67,17 @@
 	char x;
 	int i, k;
 	int randn[PAGE_SIZE];
+	int count = 0;
 	
 	for (i=0;i<PAGE_SIZE; i++)
 		randn[i] = rand();
 
 	actimes = malloc(sizeof(long));
 
-	while (*threadstart == 0 )
+	while (*threadstart == 0) {
+		if (++count > 1000000)
+			break;
 		usleep(1);
+	}
 
 	if (d->rw == 0)
@@ -180,6 +181,7 @@
 	threadstart = malloc(sizeof(int));
 	*threadstart = 0;
 	data.readp = &p; data.startaddr = startaddr; data.rw = rw; data.loop = l;
+	sleep(1);
 	for (i=0; i< t; i++)
 		if(pthread_create(&pid[i], NULL, accessmm, &data))
 			perror("pthread create");
' | patch -p0 || die Failed to patch

gcc -DFILE_SIZE=$((128*1048576)) -g $DEFAULT_OPTIMISATION_LEVEL tlbflush.c -lpthread -o tlbflush || die Failed to build tlbflush binary

exit $SHELLPACK_SUCCESS
